/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2023-12-29 14:37:11
 * @Description  : 工具类，用于格式化部分数据
 */
const moment = require('moment')
const { Op } = require('sequelize')
const { FILE_FORMAT } = require('@/constants')
const Source = require('@/models/sourceModel')

/**
 * @description 当文件名冲突时，对文件名进行修改,加上时间戳
 * @param {string} filename 原始名称
 * @returns {string} newName 不重复的新名称
 */
module.exports.formatFilename = (filename, inc = false) => {
  if (inc) {
    return this.formatFilenameByInc
  }
  const timestamp = moment().format(FILE_FORMAT)
  // 获取文件后缀名
  const lastIndex = filename.lastIndexOf('.')
  let suffix = ''
  let before = filename
  if (lastIndex !== -1) {
    suffix = filename.substring(lastIndex)
    before = filename.substring(0, lastIndex)
  }
  const newName = before + '_' + timestamp + suffix
  return newName
}

module.exports.getFirstAndSuffix = (filename) => {
  let lastIndex = filename.lastIndexOf('.')
  let first = filename
  let suffix = ''
  if (lastIndex !== -1) {
    first = filename.substring(0, lastIndex)
    suffix = filename.substring(lastIndex)
  }

  return {
    first,
    suffix
  }
}

/**
 * @description 当文件名冲突时，对文件名进行修改,使用递增文件名的形式
 *  xxx.png--->xxx(1).png--->xxx(2).png
 * @param {*} parentId 父资源ID
 * @param {string} filename 要修改的文件名
 * @param {boolean} getMax 是否返回下一递增号码
 * @returns {string|number} 返回新的名称，或者下一递增序号
 */
module.exports.formatFilenameByInc = async (
  parentId,
  filename,
  getMax = false
) => {
  const { first, suffix } = this.getFirstAndSuffix(filename)

  let names = await Source.findAll({
    attributes: ['filename'],
    where: {
      filename: {
        [Op.like]: `${first}%`
      },
      parentId: BigInt(parentId),
      deleteFlag: 0
    }
  })

  let newFirst = first.replace('(', '\\(')
  newFirst = newFirst.replace(')', '\\)')

  let reg = new RegExp(`^${newFirst}\\s*(\\((\\d+)\\))?\\s*${suffix}$`)
  names = names
    .filter((item) => {
      // const { first: itemFirst, suffix: itemSuffix } = this.getFirstAndSuffix(
      //   item.filename
      // )

      // if (itemFirst === first && suffix === itemSuffix) {
      //   // 同时获取数字部分
      //   let reg = /\((\d+)\)[^\(\)]*$/
      //   const match = itemFirst.match(reg)

      //   if (match) {
      //     item.filename = Number(match[1])
      //   } else {
      //     item.filename = 0
      //   }
      //   return true
      // }
      // 这个names 即为xxx,应该满足一下正则/^first.*suffix$/

      if (reg.test(item.filename)) {
        item.filename.replace(reg, (p, p1, p2) => {
          // 如果p2为undeined，说明为xxx.png
          if (!p2) {
            item.filename = 0
          } else {
            item.filename = Number(p2)
          }
        })
        return true
      }
      return false
    })
    .map((item2) => item2.filename)

  let max = 0
  // 如果names数组为0，说明没人满足正则，也就是不重复
  if (names.length) {
    max = Math.max.apply(null, names) + 1
  }
  if (getMax) {
    return max
  }
  if (max === 0) {
    return `${first}${suffix}`
  } else {
    return `${first}(${max})${suffix}`
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 根据用户输入的序列号为文件重命名
 * @param {string} filename 文件名
 * @param {number} num 序列号
 * @returns {string} 新的文件名
 */
module.exports.getNumName = (filename, num) => {
  let lastIndex = filename.lastIndexOf('.')
  let first = filename
  let suffix = ''
  if (lastIndex !== -1) {
    first = filename.substring(0, lastIndex)
    suffix = filename.substring(lastIndex)
  }
  return `${first}(${num})${suffix}`
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 字节转换为其他单位，按最大能转换的单位算起
 * @param {string} bytes 字节数
 * @returns {string} 转换字节后的最大单位
 */
module.exports.convertFromBytes = (bytes) => {
  const units = {
    B: 1n,
    KB: 1024n,
    MB: 1024n ** 2n,
    GB: 1024n ** 3n,
    TB: 1024n ** 4n
  }

  let unit = 'B'
  let value = BigInt(bytes)

  for (const key of Object.keys(units).reverse()) {
    if (value >= units[key]) {
      unit = key
      value = value / units[key]
      break
    }
  }

  return `${value.toString()}${unit}`
}
